const {
    BrowserWindow,
    BrowserView,
    Menu,
    Tray,
    protocol,
    net,
    dialog,
    app,
    screen,
    ipcMain,
    globalShortcut,
} = require("electron/main");
const path = require("node:path");
const fs = require("node:fs");
const url = require("node:url");
const reloader = require("electron-reloader"); // 热更新
const menus = require("./src/menus/index");
const { exec } = require("child_process");
const { platform } = process;
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true"; // 禁用安全警告,否则控制台会报个警告
const browserWidth = 800;
const browserHeight = 600;
const deviationDistance = 50;
let mainWindow;
// 开启主窗口
const createMainWindow = () => {
    const icon = path.join(__dirname, "src/assets/icons/tray.png");
    mainWindow = new BrowserWindow({
        icon,
        width: browserWidth,
        height: browserHeight,
        webPreferences: {
            contextIsolation: true, // 开启隔离上下文  也可将其注释掉，值为false时，contextBridge不能使用
            nodeIntegration: true, // 允许在渲染进程中使用Node.js API
            preload: path.join(__dirname, "src/preload/index.js"), // 预加载脚本
            enableRemoteModule: true, // 允许远程模块
        },
        autoHideMenuBar: false, // 隐藏菜单栏
        // titleBarStyle: "hidden",
        // titleBarOverlay: {
        //     color: "#f5f5f5",
        //     symbolColor: "#545454",
        //     height: 40,
        // },
    });

    mainWindow.loadFile("index.html");
    mainWindow.webContents.openDevTools();
    Menu.setApplicationMenu(menus);
};
// 设置新窗口
const createNewWindow = () => {
    const newWindow = new BrowserWindow({
        width: browserWidth,
        height: browserHeight,
        webPreferences: {
            contextIsolation: true,
            nodeIntegration: true, // 允许在渲染进程中使用Node.js API
            preload: path.join(__dirname, "src/preload/index.js"), // 预加载脚本
            enableRemoteModule: true, // 允许远程模块
        },
    });
    newWindow.loadFile("./src/html/blank.html");
    const { deviationLeft, deviationTop } = setWindowPosition();
    // 每新增一个窗口，将新窗口位置偏移
    newWindow.setPosition(deviationLeft, deviationTop);
    newWindow.webContents.openDevTools();
};
// 设置嵌套窗口
const createNestingWindow = () => {
    const view = new BrowserView();
    view.setBounds({ x: 100, y: 250, width: 600, height: 200 });
    view.webContents.loadFile(path.join(__dirname, "src/html/nesting.html"));
    view.webContents.openDevTools();
    mainWindow.setBrowserView(view);
};
// 计算新窗口定位点
const setWindowPosition = () => {
    const { width, height } = screen.getPrimaryDisplay().workAreaSize;
    const deviationCount = BrowserWindow.getAllWindows().length - 1;
    const deviationLeft =
        (width - browserWidth) / 2 + deviationDistance * deviationCount;
    const deviationTop =
        (height - browserHeight) / 2 + deviationDistance * deviationCount;
    console.log(deviationCount, "deviationCount");
    return { deviationLeft, deviationTop };
};
// 注册全局快捷键
const createGlobalShortcut = () => {
    commandList.forEach((item) => {
        const { command, callback } = item;
        globalShortcut.register(command, () => {
            callback();
        });
    });
    // globalShortcut.register("CmdOrCtrl+Shift+N", () => {
    //     createNewWindow();
    // });
};
// 关闭当前窗口
const closeActiveWindow = () => {
    const activeWindow = BrowserWindow.getFocusedWindow();
    if (activeWindow) {
        activeWindow.close();
    }
};
// 打开读取文件窗口
const openFile = () => {
    dialog
        .showOpenDialog({
            properties: ["openFile", "multiSelections"],
            filters: [
                { name: "Images", extensions: ["jpg", "png", "gif"] },
                { name: "Movies", extensions: ["mkv", "avi", "mp4"] },
            ],
        })
        .then((result) => {
            if (!result.canceled) {
                const filePath = result.filePaths;
                const list = [];
                const readFileFun = async (filePath) => {
                    for (const path of filePath) {
                        const fileContent = await fs.promises.readFile(path);
                        const data = fileContent.toString("base64");
                        list.push(data);
                    }
                    mainWindow.webContents.send("openFileMes", list);
                };
                readFileFun(filePath);
            }
        });
};
// 自定义协议(其实就是拦截器，类似于axios)
const customProtocol = () => {
    protocol.handle("myapp", (request) => {
        console.log(request.url);
        // <img src="myapp://src/assets/imgs/boy.png" alt=""></img>
        // index.html中图片路径如上，将以“myapp”开头的资源进行拦截，并将“myapp://”替换为空
        const filePath = request.url.replace("myapp://", "");
        const p = path.join(__dirname, filePath);
        const l = url.pathToFileURL(p).toString();
        // console.log(l, "l");
        return net.fetch(l);
    });
};
// 调用系统键盘;
const openSystemKeyboard = () => {
    // window: win32
    // mac: darwin
    // linux: linux
    const commandStr = platform === "win32" ? "osk.exe" : "onboard"; // onboard是Linux下的命令
    exec(commandStr, (error, stdout, stderr) => {
        if (error) {
            console.log(`打开键盘报错: ${error.message}`);
            return;
        }
    });
};
// 最小化到托盘
const minimizeToTray = () => {
    const tray = new Tray(path.join(__dirname, "src/assets/icons/tray.png"));
    const contextMenu = Menu.buildFromTemplate([
        {
            label: "显示",
            // type: "normal",
            click: () => {
                mainWindow.show();
            },
        },
        {
            label: "最大化",
            click: () => {
                mainWindow.maximize();
            },
        },
        {
            label: "最小化",
            click: () => {
                const browserList = BrowserWindow.getAllWindows();
                browserList.forEach((item) => {
                    item.minimize();
                });
            },
        },
        {
            label: "退出",
            click: () => {
                app.quit();
            },
        },
    ]);
    tray.setToolTip("这是一个托盘");
    tray.setContextMenu(contextMenu);
};
const commandList = [
    {
        command: "CmdOrCtrl+shift+N",
        callback: () => {
            createNewWindow();
        },
    },
    {
        command: "CmdOrCtrl+shift+W",
        callback: () => {
            closeActiveWindow();
        },
    },
    {
        command: "CmdOrCtrl+O",
        callback: () => {
            openFile();
        },
    },
];
protocol.registerSchemesAsPrivileged([
    {
        scheme: "myapp",
        privileges: {
            secure: true,
            standard: true,
            supportFetchAPI: true,
            stream: true,
        },
    },
]);
app.whenReady().then(() => {
    customProtocol();
    createGlobalShortcut();
    createMainWindow();
    app.on("activate", function () {
        if (BrowserWindow.getAllWindows().length === 0) {
            createMainWindow();
        }
    });
    // 主进程监听来自渲染进程的消息
    ipcMain.handle("invokeHandleMessage", (event) => {
        return "heihei";
    });
    ipcMain.on("sendOnMessage", (event, arg) => {
        console.log("渲染进程通知主进程");
    });
    ipcMain.on("addBrowserWindow", (event, arg) => {
        console.log(arg, "渲染进程通知主进程：新增窗口");
        createNewWindow();
    });
    ipcMain.on("addBrowserView", (event, arg) => {
        console.log(arg, "渲染进程通知主进程：主界面展示嵌套窗口");
        createNestingWindow();
    });
    ipcMain.on("openKeyboard", (event, arg) => {
        console.log(arg, "渲染进程通知主进程：打开系统键盘");
        openSystemKeyboard();
    });
    // 监听菜单栏点击
    app.on("click-menu-item", (arg) => {
        console.log(arg, "监听到菜单栏点击-主进程收到的信息");
        const target = commandList.find((item) => item.command === arg);
        if (target) {
            const { callback } = target;
            callback();
        }
    });
    minimizeToTray();
    reloader(module);
});
app.on("will-quit", () => {
    globalShortcut.unregisterAll(); // 解绑快捷键
});
app.on("window-all-closed", function () {
    if (process.platform !== "darwin") {
        app.quit();
    }
});
